package Java7_Concurrency_Cookbook.concurrent_custom.custom_runnable_scheduled_future;

import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author lixiangke
 * @date 2017/11/24
 */
public class MyScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {

    public MyScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize);
    }

    /**
     * 想要实现自定义定时任务, 必须实现自定义的定时执行器. <br/>
     * 为了在定时执行器中使用MyScheduledTask, 我们必须覆盖decorateTask()方法. <br/>
     * 覆盖这个方法将缺省定时任务替换为MyScheduledTask任务<br/>
     */
    @Override
    protected <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable,
                                                          RunnableScheduledFuture<V> task) {
        MyScheduledTask<V> myTask = new MyScheduledTask<>(runnable, null, task,
                this);
        return myTask;
    }

    @Override
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay,
                                                  long period, TimeUnit unit) {
        ScheduledFuture<?> task = super.scheduleAtFixedRate(command, initialDelay, period, unit);
        MyScheduledTask<?> myTask = (MyScheduledTask<?>) task;
        myTask.setPeriod(TimeUnit.MILLISECONDS.convert(period, unit));
        return task;
    }
}
